import React, { Component } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Select,
  Button, DatePicker, Table, Modal, Menu, Dropdown, Icon } from 'antd';
import moment from 'moment';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './UserManagement.less';
import AddMaster from './AddMaster';
import ShowMasterInfo from './ShowMasterInfo';
import ChangeMasterPwd from './ChangeMasterPwd';
import globalConstant from '../../utils/globalConstant';

const FormItem = Form.Item;
const { Option } = Select;


@connect(({ masterManage, loading }) => ({
  masterManage,
  loading: loading.models.masterManage,
}))
@Form.create()
export default class MasterManagement extends Component {
  state = {
    showMasterInfoVisible: false,
    showAddMasterVisible: false,
    showMasterChangePwdVisible: false,
    masterId: undefined,
    masterInfo: {},
    pageNum: globalConstant.paging.pageNum,
    pageSize: globalConstant.paging.pageSize,
    form: {},
  };
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'masterManage/fetch',
      payload: {
        pageNum: globalConstant.paging.pageNum,
        pageSize: globalConstant.paging.pageSize,
      },
    });
  }

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.state.form,
    };
    this.setState({
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
    dispatch({
      type: 'masterManage/fetch',
      payload: params,
    });
  }
  handleSearch = (e) => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const rangeValue = fieldsValue.date || undefined;
      dispatch({
        type: 'masterManage/fetch',
        payload: {
          crtTimeEnd: rangeValue && rangeValue[1].valueOf(),
          crtTimeStart: rangeValue && rangeValue[0].valueOf(),
          keywordsNames: fieldsValue.keywordsNames || null,
          keywordsValue: fieldsValue.keywordsValue || null,
          accountStatus: fieldsValue.status || null,
        },
      });
      this.setState({
        form: {
          crtTimeEnd: rangeValue && rangeValue[1].valueOf(),
          crtTimeStart: rangeValue && rangeValue[0].valueOf(),
          keywordsNames: fieldsValue.keywordsNames || null,
          keywordsValue: fieldsValue.keywordsValue || null,
          accountStatus: fieldsValue.status || null,
        },
      });
    });
  }
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      form:{},
    });
    dispatch({
      type: 'masterManage/fetch',
      payload: {
        pageNum: globalConstant.paging.pageNum,
        pageSize: globalConstant.paging.pageSize,
      },
    });
  }
  handleShowMasterInfo = (value) => {
    this.setState({
      showMasterInfoVisible: true,
      masterId: value,
    });
  };
  handleDeleteMaster = (text) => {
    Modal.confirm({
      title: '确定删除?',
      content: `确定删除用户名为: [${text.userName}]`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: 'masterManage/deleteMaster',
          payload: {
            id: text.id,
          },
          callback: () => {
            this.props.dispatch({
              type: 'masterManage/fetch',
              payload: {
                pageNum: this.state.pageNum,
                pageSize: this.state.pageSize,
                ...this.state.form,
              },
            });
          },
        });
      },
    });
  };
  handleCheckMaster = (text) => {
    Modal.confirm({
      title: '确定修改审核状态?',
      content: `确定修改 [${text.userName}] 的审核状态`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: 'masterManage/updateMasterStatus',
          payload: {
            id: text.id,
            accountStatus: text.accountStatus === 'USER_ACCOUNT_STATUS_NORMAL' ? 'USER_ACCOUNT_STATUS_LOCK' : 'USER_ACCOUNT_STATUS_NORMAL',
          },
          callback: () => {
            this.props.dispatch({
              type: 'masterManage/fetch',
              payload: {
                pageNum: this.state.pageNum,
                pageSize: this.state.pageSize,
                ...this.state.form,
              },
            });
          },
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  handleAddMasterModal= () => {
    this.setState({
      showAddMasterVisible: true,
    });
  }
  handleShowInfoModalCancel = () => {
    this.setState({
      showMasterInfoVisible: false,
    });
  }
  handleAddMasterModalCancel = () => {
    this.setState({
      showAddMasterVisible: false,
    });
  }
  /*
    处理子组件的关闭Modal事件
   */
  handleModal = () => {
    this.setState({
      showMasterInfoVisible: false,
    });
    this.props.dispatch({
      type: 'masterManage/fetch',
      payload: {
        pageNum: this.state.pageNum,
        pageSize: this.state.pageSize,
      },
    });
  }
  handleAddChildModal = () => {
    this.setState({
      showAddMasterVisible: false,
    });
    this.props.dispatch({
      type: 'masterManage/fetch',
      payload: {
        pageNum: this.state.pageNum,
        pageSize: this.state.pageSize,
      },
    });
  }
  handleChangeMasterPwdModal = (text) => {
    this.setState({
      showMasterChangePwdVisible: true,
      masterInfo: text,
    });
  }
  handleChangeMasterPwdCancel = () => {
    this.setState({
      showMasterChangePwdVisible: false,
    });
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字">
              {getFieldDecorator('keywordsValue')(
                <Input placeholder="请输入搜索关键字" />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select style={{ width: '100%' }}>
                  <Option value={null}>全部</Option>
                  <Option value="USER_ACCOUNT_STATUS_NORMAL">正常</Option>
                  <Option value="USER_ACCOUNT_STATUS_LOCK">冻结</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="创建日期">
              {getFieldDecorator('date')(
                <DatePicker.RangePicker
                  style={{ width: '100%' }}
                  format={globalConstant.dateFormat}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字类型">
              {getFieldDecorator('keywordsNames')(
                <Select
                  mode="multiple"
                >
                  <Select.Option value="userName">姓名</Select.Option>
                  <Select.Option value="userMobile">手机号码</Select.Option>
                  <Select.Option value="serviceAddrInstruction">服务范围</Select.Option>
                  <Select.Option value="userIdcard">身份证号</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={16} style={{ textAlign: 'right' }}>
            <span className={styles.submitButtons}>
              <Button icon="search" type="primary" htmlType="submit" >查询</Button>
              <Button icon="reload" style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  render() {
    const { masterManage: { masterUserList }, loading } = this.props;
    const {
      showMasterInfoVisible,
      showAddMasterVisible,
      showMasterChangePwdVisible,
      masterId,
      masterInfo,
    } = this.state;
    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        width: '10%',
      },
      {
        title: '姓名',
        dataIndex: 'userName',
        width: '15%',
      },
      {
        title: '服务区域',
        dataIndex: 'serviceAddrInstruction',
        width: '20%',
      },
      {
        title: '手机号码',
        dataIndex: 'userMobile',
        width: '15%',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: '15%',
        render: (text) => {
          return text !== 0 ? moment(text.updateTime).format(globalConstant.dateFormat) : '日期无效';
        },
      },
      {
        title: '账号状态',
        render: (text) => {
          return (
            <Button
              type={text.accountStatus === 'USER_ACCOUNT_STATUS_NORMAL' ? 'danger' : 'primary'}
              onClick={() => { this.handleCheckMaster(text); }}
              icon={text.accountStatus === 'USER_ACCOUNT_STATUS_NORMAL' ? 'close' : 'check'}
            >
              {text.accountStatus === 'USER_ACCOUNT_STATUS_NORMAL' ? '禁用' : '启用'}
            </Button>
          );
        },
      },
      {
        title: '操作',
        key: 'key',
        render: (text) => {
          const menu = (
            <Menu>
              <Menu.Item key="1">
                <Button
                  onClick={() => { this.handleShowMasterInfo(text.id); }}
                  icon="info"
                >
                  查看详情
                </Button>
              </Menu.Item>
              <Menu.Item key="2">
                <Button
                  type="danger"
                  icon="delete"
                  onClick={() => { this.handleDeleteMaster(text); }}
                >
                  删除纪录
                </Button>
              </Menu.Item>
              <Menu.Item key="3">
                <Button
                  type="danger"
                  icon="lock"
                  onClick={() => { this.handleChangeMasterPwdModal(text); }}
                >
                  修改密码
                </Button>
              </Menu.Item>
            </Menu>
          );
          return (
            <Dropdown overlay={menu}>
              <Button style={{ width: 100 }}>
                操作 <Icon type="down" />
              </Button>
            </Dropdown>
          );
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: masterUserList.totals,
      current: masterUserList.currentPage,
      ...globalConstant.pagingFormat,
    };
    return (
      <PageHeaderLayout title="师傅管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>
            <Card bordered>
              <div className={styles.tableListOperator}>
                <Button icon="plus" type="primary" onClick={() => this.handleAddMasterModal()}>
                  新建
                </Button>
              </div>
              <Table
                bordered
                loading={loading}
                rowKey={record => record.id}
                dataSource={masterUserList && masterUserList.items}
                columns={columns}
                pagination={paginationProps}
                onChange={this.handleStandardTableChange}
              />
            </Card>
          </div>
        </Card>
        <Modal
          visible={showMasterInfoVisible}
          title="查看详情"
          footer={null}
          width="60%"
          onCancel={() => this.handleShowInfoModalCancel()}
          destroyOnClose
        >
          <ShowMasterInfo masterId={masterId} handCancel={this.handleModal.bind(this)} />
        </Modal>
        <Modal
          visible={showAddMasterVisible}
          title="添加师傅"
          footer={null}
          width="60%"
          onCancel={() => this.handleAddMasterModalCancel()}
          destroyOnClose
        >
          <AddMaster handleAddModal={this.handleAddChildModal.bind(this)} />
        </Modal>
        <Modal
          visible={showMasterChangePwdVisible}
          title="修改密码"
          footer={null}
          width="60%"
          onCancel={() => this.handleChangeMasterPwdCancel()}
          destroyOnClose
        >
          <ChangeMasterPwd
            masterInfo={masterInfo}
            handleChangePwdModal={this.handleChangeMasterPwdCancel.bind(this)}
          />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
